/**
* @file response_get_image.cpp
*
*	 Nel file response_get_image.cpp viene implementata la classe Response_Get_Image
*	
* @author Favale Angelo
* @author Fagioli Alessio
*
* @version 1.0
*/

#include "response_get_image.h"

Response_Get_Image::Response_Get_Image(host peer){

	strcpy(this->name, "Get_Image");
	strcpy(this->entita.ip,peer.ip);
	this->entita.porta=peer.porta;
	this->entita.s=peer.s;

}


bool Response_Get_Image::receive_image (char* nome_file, int len_file)
{
	char buffer[BUFFER_SIZE];
	FILE *f;
	int i,n;
	sprintf(buffer,"foto/%s",nome_file);

	f=fopen(buffer,"wb");
	if(f==NULL)
	{			
		printf("Errore apertura file\n");
		return false;
	}
	
	memset(buffer,0,BUFFER_SIZE);
	
	n=0;

	while(n<len_file)
	{
		i=recv(entita.s,buffer,sizeof(buffer),0);
		fwrite(buffer,1,i,f);
		n+=i;		
	}			

	fclose(f);

	return true;

}


bool Response_Get_Image::code_request(char * buffer,char * nome_file)
{
	
	sprintf(buffer,"%s;%s#",this->name,nome_file);
	
	if (send(entita.s,buffer,strlen(buffer),0)==-1)
		{		
		printf("Errore invio\n");
		return false;
		}
	
	return true;

}


bool Response_Get_Image::decode_request(char * buffer,char * nome_file)
{
	int i=0;
	
	while(buffer[i]!='#' && i<BUFFER_SIZE)
	{
		nome_file[i]=buffer[i];
		i++;
	}
	nome_file[i]='\0';
	
	if(i==BUFFER_SIZE)
		return false;
	else
		return true;
}


bool Response_Get_Image::code_response(int len_file, bool verify)
{
	
	char buf[BUFFER_SIZE];

	if(!verify)
		strcpy(buf,"0#");
	else
		sprintf(buf,"1;%d#",len_file);
	
	
	if (send(entita.s,buf,strlen(buf),0)==-1)
		{		
		printf("Errore invio\n");
		return false;
		}
	return true;
}



bool Response_Get_Image::decode_response(char * buf, char * lunghezza_file){

	int i=2;

	recv (entita.s,&buf[0],2,0);

	if(buf[0]=='0')
		return false;
	
	do
	{
		recv(entita.s,&buf[i],1,0);
		lunghezza_file[i-2]=buf[i];
		
	}while(buf[i++]!='#' && i<BUFFER_SIZE);

	if(i==BUFFER_SIZE)
		return false;

	lunghezza_file[i-1]='\0';

	return true;
}



